<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>instanceof实现</title>
  </head>
  <script>
    // instanceof 的核心是通过原型链的查找实现的，本质就是在判断
    function myInstanceof(obj, constructor) {
      // 先判断基本类型和null的情况直接返回false
      if (obj === null || typeof obj !== 'object') {
        return false;
      }
      // 获取constructor的原型
      prototype = constructor.prototype;
      let proto = Object.getPrototypeOf(obj);
      while (proto !== null) {
        if (proto === prototype) {
          return true;
        }
        proto = Object.getPrototypeOf(proto);
      }
      return false;
    }

    function a() {}
    console.log(a instanceof Object, 'instanceof');
    console.log([] instanceof Object, 'instanceof');
    console.log(null instanceof Object, 'instanceof');
    console.log(myInstanceof([], Object), 'myInstanceof');
    console.log(myInstanceof([], Array));
    console.log(myInstanceof({}, Object));
    console.log(myInstanceof(null, Object));
    console.log(myInstanceof(new Date(), Object));
    console.log(myInstanceof(a, Function));

    // 还可以通过prototype.isPrototypeOf 直接检查a 是否在b原型上
    function myInstanceOf2(obj, constructor) {
      if (obj === null || typeof obj !== 'object') {
        return false;
      }

      return constructor.prototype.isPrototypeOf(obj);
    }

    console.log(myInstanceOf2([], Object), 'myInstanceOf2');
    console.log(myInstanceOf2([], Array));
    console.log(myInstanceOf2({}, Object));
    console.log(myInstanceOf2(null, Object));
    console.log(myInstanceOf2(new Date(), Object));
    console.log(myInstanceOf2(a, Function));
  </script>
  <body></body>
</html>
